<template>
  <div class="page-container">
    <!-- 顶部导航栏 -->
    <TopNav />

    <!-- 页面主体内容 -->
    <div class="card-container">
      <el-card class="full-height-card" shadow="always">
        <template #header>
          <div class="card-header">
            <h2>设置本单位信息</h2>
          </div>
        </template>

        <el-form :model="form" label-width="160px" class="unit-info-form">
          <el-form-item label="本使用单位代码">
            <el-input v-model="form.unitCode" placeholder="请输入单位代码" :disabled="!editing"></el-input>
          </el-form-item>

          <el-form-item label="本使用单位名称">
            <el-input v-model="form.unitName" placeholder="请输入单位名称" :disabled="!editing"></el-input>
          </el-form-item>

          <el-form-item label="本使用单位前缀">
            <el-input v-model="form.unitPrefix" placeholder="请输入单位前缀" :disabled="!editing"></el-input>
          </el-form-item>

          <el-form-item label="本使用单位属于">
            <el-select v-model="form.unitType" placeholder="请选择单位类型" :disabled="!editing">
              <el-option label="铁路单位" value="railway"></el-option>
              <el-option label="其他" value="other"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="自动备份文件夹">
            <div class="path-input-group">
              <el-input v-model="form.autoBackupPath" placeholder="请选择备份目录" :disabled="!editing"></el-input>
              <el-button type="primary" :disabled="!editing" @click="handleSelectDirectory">选择目录</el-button>
            </div>
          </el-form-item>

          <el-form-item class="submit-item">
            <template v-if="!editing">
              <el-button type="primary" class="submit-button" @click="handleEdit">修改</el-button>
            </template>
            <template v-else>
              <el-button type="default" class="submit-button" @click="handleCancel">还原</el-button>
              <el-button type="primary" class="submit-button" @click="handleConfirm">确认</el-button>
            </template>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
// 引入组件
import TopNav from './navmenu.vue'
// 引入数据库工具
import db from '../../utils/database.js'
// 引入Element Plus的消息组件
import { ElMessage } from 'element-plus'

// 表单数据
const form = ref({
  unitCode: '',
  unitName: '',
  unitPrefix: '',
  unitType: '',
  autoBackupPath: '',
  monthlyReportPath: ''
})

// 处理选择目录按钮点击
const handleSelectDirectory = async () => {
  try {
    // 获取当前项目路径作为默认路径
    const projectPathResult = await window.electronAPI.invoke('get-project-path')
    
    // 检查获取项目路径是否成功
    if (!projectPathResult.success) {
      throw new Error('获取项目路径失败: ' + projectPathResult.error)
    }
    
    const projectPath = projectPathResult.path
    
    // 打开目录选择对话框
    const dialogResult = await window.electronAPI.invoke('show-open-dialog', {
      properties: ['openDirectory'],
      defaultPath: projectPath,
      title: '选择自动备份文件夹'
    })
    
    // 检查对话框操作是否成功
    if (!dialogResult.success) {
      throw new Error('打开目录选择对话框失败: ' + dialogResult.error)
    }
    
    // 如果用户选择了目录
    if (!dialogResult.canceled && dialogResult.filePaths && dialogResult.filePaths.length > 0) {
      form.value.autoBackupPath = dialogResult.filePaths[0]
    }
  } catch (error) {
    ElMessage.error('选择目录失败，请重试')
  }
}

// 编辑状态
const editing = ref(false)
// 原始数据备份
const originalForm = ref({})

// 处理编辑按钮点击
const handleEdit = () => {
  originalForm.value = { ...form.value }
  editing.value = true
}

// 处理还原按钮点击
const handleCancel = () => {
  form.value = { ...originalForm.value }
  editing.value = false
}

// 处理确认按钮点击
const handleConfirm = async () => {
  try {
    const sessionId = localStorage.getItem('sessionId')
    if (!sessionId) {
      throw new Error('未找到会话ID，请重新登录')
    }
    
    const sessionResult = await window.electronAPI.invoke('auth-verify-session', { sessionId })
    if (!sessionResult.success || !sessionResult.isAuthenticated) {
      throw new Error('会话验证失败，请重新登录')
    }
    
    const username = sessionResult.username
    
    const userResult = await db.query(
      'SELECT id, unit_code, unit_name, unit_prefix, unit_belong, backup FROM users WHERE LOWER(username) = LOWER(?)', 
      [username]
    )
    
    if (userResult.length === 0) {
      // 用户不存在，执行插入操作
      await db.insert(`
        INSERT INTO users (
          username,
          unit_code,
          unit_name,
          unit_prefix,
          unit_belong,
          backup
        ) VALUES (?, ?, ?, ?, ?, ?)
      `, [
        username,
        form.value.unitCode,
        form.value.unitName,
        form.value.unitPrefix,
        form.value.unitType,
        form.value.autoBackupPath
      ])
      
      ElMessage.success('用户信息已创建')
    } else {
      // 用户存在，执行更新操作
      const userId = userResult[0].id
      await db.update(`
        UPDATE users 
        SET unit_code = ?, 
            unit_name = ?, 
            unit_prefix = ?, 
            unit_belong = ?, 
            backup = ? 
        WHERE id = ?
      `, [
        form.value.unitCode,
        form.value.unitName,
        form.value.unitPrefix,
        form.value.unitType,
        form.value.autoBackupPath,
        userId
      ])
      
      ElMessage.success('单位信息已更新')
    }
    
    editing.value = false
  } catch (error) {
    ElMessage.error(`操作失败: ${error.message}`)
  }
}

// 初始化表单数据
const initForm = async () => {
  try {
    const sessionId = localStorage.getItem('sessionId')
    if (!sessionId) {
      throw new Error('未找到会话ID，请重新登录')
    }
    
    const sessionResult = await window.electronAPI.invoke('auth-verify-session', { sessionId })
    if (!sessionResult.success || !sessionResult.isAuthenticated) {
      throw new Error('会话验证失败，请重新登录')
    }
    
    const username = sessionResult.username
    
    const userResult = await db.query(
      'SELECT id, unit_code, unit_name, unit_prefix, unit_belong, backup FROM users WHERE LOWER(username) = LOWER(?)', 
      [username]
    )
    
    if (userResult.length === 0) {
      form.value = {
        unitCode: '',
        unitName: '',
        unitPrefix: '',
        unitType: '',
        autoBackupPath: '',
        monthlyReportPath: ''
      }
    } else {
      const user = userResult[0]
      form.value = {
        unitCode: user.unit_code || '',
        unitName: user.unit_name || '',
        unitPrefix: user.unit_prefix || '',
        unitType: user.unit_belong || '',
        autoBackupPath: user.backup || '',
        monthlyReportPath: ''
      }
    }
    
    originalForm.value = { ...form.value }
  } catch (error) {
  }
}

initForm()
</script>

<style scoped>
/* 原有样式保持不变 */
.page-container {
  display: flex;
  flex-direction: column;
  height: 98vh;
  background: #f5f6f7;
}

.card-container {
  flex: 1;
  padding: 20px;
  box-sizing: border-box;
  overflow: hidden;
}

.full-height-card {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: white;
}

.card-header {
  display: flex;
  align-items: center;
  padding: 0;
}

.card-header h2 {
  margin: 0;
  font-size: 22px;
  font-weight: 700;
  color: #333;
}

:deep(.el-card__header) {
  min-height: 80px;
  display: flex;
  align-items: center;
  padding: 0 40px;
  flex-shrink: 0;
  background: white;
  border-bottom: 2px solid #f0f0f0;
}

:deep(.el-card__body) {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #f5f6f7;
  overflow: auto;
}

.unit-info-form {
  width: 100%;
  max-width: 850px;
}

:deep(.el-form-item) {
  margin-bottom: 42px;
  display: flex;
  align-items: center;
}

:deep(.el-form-item__label) {
  width: 200px !important;
  font-size: 16px;
  font-weight: 700;
  color: #333;
  text-align: right;
  padding-right: 30px;
  flex-shrink: 0;
  line-height: 1.6;
}

:deep(.el-form-item__content) {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 12px;
  min-width: 0;
}

:deep(.el-input__wrapper) {
  width: 100%;
  min-width: 280px;
}

:deep(.el-input) {
  --el-input-height: 40px;
}

:deep(.el-input__inner) {
  font-size: 14px;
}

:deep(.el-select) {
  width: 100%;
  min-width: 280px;
}

.path-input-group {
  display: flex;
  gap: 12px;
  width: 100%;
  align-items: center;
}

.path-input-group .el-input {
  flex: 1;
  min-width: 0;
}

.path-input-group .el-button {
  flex-shrink: 0;
  width: 120px;
  height: 44px;
  font-size: 15px;
  font-weight: 500;
}

.submit-item {
  margin-top: 60px;
  justify-content: center;
}

:deep(.submit-item .el-form-item__content) {
  justify-content: right;
  padding-left: 215px;
  display: flex;
  gap: 10px;
}

.submit-button {
  width: 200px;
  height: 48px;
  font-size: 17px;
  font-weight: 600;
  border-radius: 6px;
  letter-spacing: 1px;
}

:deep(.submit-button:hover) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 82, 204, 0.3);
}

@media (max-width: 1000px) {
  .unit-info-form {
    max-width: 750px;
  }

  :deep(.el-form-item__label) {
    width: 180px !important;
    font-size: 15px;
    padding-right: 25px;
  }

  :deep(.el-card__body) {
    padding: 20px 20px;
  }
}

@media (max-width: 768px) {
  :deep(.el-form-item) {
    flex-direction: column;
    align-items: flex-start;
    margin-bottom: 36px;
  }

  :deep(.el-form-item__label) {
    width: 100% !important;
    text-align: left;
    margin-bottom: 12px;
    padding-right: 0;
    font-size: 15px;
  }

  :deep(.el-form-item__content) {
    width: 100%;
  }

  .path-input-group {
    flex-direction: column;
  }

  .path-input-group .el-button {
    width: 100%;
  }
}
</style>